<template>
  <div class="device-template">
    <div class="page-header">
      <h2>设备模板管理</h2>
      <p>管理设备导入模板，建立设备数据库</p>
    </div>

    <!-- 选择操作页面 -->
    <el-card class="main-card" v-if="currentStep === 'main'">
      <template #header>
        <h3>设备模板管理</h3>
      </template>

      <div class="operation-selection">
        <div class="operation-card-container">
          <!-- 导入模板选项 -->
          <el-card class="operation-card" shadow="hover" @click="showUploadDialog">
            <div class="operation-content">
              <el-icon size="48" color="#409EFF"><UploadFilled /></el-icon>
              <h4>导入新模板</h4>
              <p>上传Excel设备模板文件，建立新的设备数据库</p>
            </div>
          </el-card>

          <!-- 使用历史数据选项 -->
          <el-card class="operation-card" shadow="hover" @click="viewHistoryData">
            <div class="operation-content">
              <el-icon size="48" color="#67C23A"><View /></el-icon>
              <h4>查看历史数据</h4>
              <p>查看已导入的设备模板数据，或了解如何开始导入</p>
            </div>
          </el-card>
        </div>
      </div>
    </el-card>

    <!-- 历史数据展示页面 -->
    <el-card class="main-card" v-if="currentStep === 'history'">
      <template #header>
        <div class="card-header">
          <h3>历史设备数据</h3>
          <div class="header-actions">
            <el-button @click="currentStep = 'main'">返回</el-button>
            <el-button v-if="hasHistoryData" type="primary" @click="showUploadDialog">
              重新导入模板
            </el-button>
            <el-button
              type="success"
              :disabled="!hasHistoryData"
              @click="continueWithHistory"
            >
              使用历史设备模板
            </el-button>
          </div>
        </div>
      </template>

      <!-- 数据统计信息 -->
      <div class="data-summary" v-if="hasHistoryData">
        <el-descriptions :column="4" :border="true">
          <el-descriptions-item label="厂站数量">{{
            stationGroups.length
          }}</el-descriptions-item>
          <el-descriptions-item label="设备总数">{{
            devices.length
          }}</el-descriptions-item>
          <el-descriptions-item label="受令单位数">{{
            commandingUnits.length
          }}</el-descriptions-item>
          <el-descriptions-item label="最后更新时间">{{
            lastUpdateTime
          }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 无历史数据提示 -->
      <div class="no-data-hint" v-if="!hasHistoryData">
        <el-empty description="暂无历史设备模板数据" :image-size="120">
          <template #description>
            <div class="empty-description">
              <h4>暂无历史设备模板数据</h4>
              <p>系统中还没有导入过设备模板，无法查看历史数据</p>
              <p>请先上传《启动方案设备导入模板》Excel文件来建立设备数据库</p>
              <p class="empty-tip">支持 .xlsx 格式，文件大小不超过 10MB</p>
            </div>
          </template>
          <div class="empty-actions">
            <el-button type="primary" size="large" @click="showUploadDialog">
              <el-icon><UploadFilled /></el-icon>
              立即上传设备模板
            </el-button>
          </div>
        </el-empty>
      </div>

      <!-- 按厂站分组展示设备数据 -->
      <div v-if="hasHistoryData" class="history-data">
        <div class="search-bar">
          <el-input
            v-model="searchText"
            placeholder="搜索厂站或设备"
            style="width: 300px"
            clearable
          />
        </div>

        <div
          v-for="station in filteredStationGroups"
          :key="station.name"
          class="station-group"
        >
          <h4 class="station-title">{{ station.name }}</h4>

          <!-- 受令单位 -->
          <el-collapse>
            <el-collapse-item title="受令单位" name="commanding">
              <el-table :data="station.commandingUnits" size="small" stripe>
                <el-table-column prop="unitName" label="受令单位名称" />
                <el-table-column prop="updatedTime" label="更新时间" width="180">
                  <template #default="scope">
                    {{ formatTime(scope.row.updatedTime) }}
                  </template>
                </el-table-column>
              </el-table>
            </el-collapse-item>

            <el-collapse-item title="线路设备" name="line">
              <el-table :data="station.lineDevices" size="small" stripe>
                <el-table-column prop="voltageLevel" label="电压等级" width="100" />
                <el-table-column prop="deviceName" label="设备名称" />
                <el-table-column prop="deviceCode" label="设备编号" />
                <el-table-column prop="deviceType" label="设备类型" />
                <el-table-column
                  prop="deviceDoubleCode"
                  label="设备双编"
                  min-width="200"
                />
                <el-table-column prop="updatedTime" label="更新时间" width="180">
                  <template #default="scope">
                    {{ formatTime(scope.row.updatedTime) }}
                  </template>
                </el-table-column>
              </el-table>
            </el-collapse-item>

            <el-collapse-item title="主变设备" name="transformer">
              <el-table :data="station.transformerDevices" size="small" stripe>
                <el-table-column prop="voltageLevel" label="电压等级" width="100" />
                <el-table-column prop="deviceName" label="设备名称" />
                <el-table-column prop="deviceCode" label="设备编号" />
                <el-table-column prop="deviceType" label="设备类型" />
                <el-table-column
                  prop="deviceDoubleCode"
                  label="设备双编"
                  min-width="200"
                />
                <el-table-column prop="updatedTime" label="更新时间" width="180">
                  <template #default="scope">
                    {{ formatTime(scope.row.updatedTime) }}
                  </template>
                </el-table-column>
              </el-table>
            </el-collapse-item>

            <el-collapse-item title="母线及附属设备" name="bus">
              <el-table :data="station.busDevices" size="small" stripe>
                <el-table-column prop="voltageLevel" label="电压等级" width="100" />
                <el-table-column prop="deviceName" label="设备名称" />
                <el-table-column prop="deviceCode" label="设备编号" />
                <el-table-column prop="deviceType" label="设备类型" />
                <el-table-column
                  prop="deviceDoubleCode"
                  label="设备双编"
                  min-width="200"
                />
                <el-table-column prop="updatedTime" label="更新时间" width="180">
                  <template #default="scope">
                    {{ formatTime(scope.row.updatedTime) }}
                  </template>
                </el-table-column>
              </el-table>
            </el-collapse-item>

            <el-collapse-item title="补充设备" name="supplement">
              <el-table :data="station.supplementDevices" size="small" stripe>
                <el-table-column prop="voltageLevel" label="电压等级" width="100" />
                <el-table-column prop="deviceName" label="设备名称" />
                <el-table-column prop="deviceCode" label="设备编号" />
                <el-table-column prop="deviceType" label="设备类型" />
                <el-table-column
                  prop="deviceDoubleCode"
                  label="设备双编"
                  min-width="200"
                />
                <el-table-column prop="updatedTime" label="更新时间" width="180">
                  <template #default="scope">
                    {{ formatTime(scope.row.updatedTime) }}
                  </template>
                </el-table-column>
              </el-table>
            </el-collapse-item>
          </el-collapse>
        </div>
      </div>
    </el-card>

    <!-- 上传对话框 -->
    <el-dialog
      v-model="uploadDialogVisible"
      title="重新导入设备模板"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="upload-dialog-content">
        <el-alert
          v-if="do_clear"
          title="清空导入"
          type="warning"
          :closable="false"
          show-icon
        >
          此操作会清空历史数据，以新导入文档设备和受令单位作为模板，请确认是否继续。
        </el-alert>
        <el-alert
          v-if="!do_clear"
          title="新增导入"
          type="warning"
          :closable="false"
          show-icon
        >
          基于原有设备和受令单位，按导入文档新增数据，请确认是否继续。
        </el-alert>
        <el-switch
          v-model="do_clear"
          class="mb-2"
          active-text="清空导入"
          inactive-text="新增导入"
        />
        <br />

        <div class="upload-area" :class="{ 'mt-20': hasHistoryData }">
          <el-upload
            drag
            :auto-upload="false"
            :on-change="handleFileChange"
            :file-list="fileList"
            accept=".xlsx"
            :limit="1"
            class="upload-dragger"
          >
            <el-icon class="upload-icon"><UploadFilled /></el-icon>
            <div class="upload-text">
              <p>拖拽《启动方案设备导入模板》.xlsx文件到此处</p>
              <p class="upload-tip">支持 .xlsx 格式，文件大小不超过 10MB</p>
            </div>
          </el-upload>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="uploadDialogVisible = false">取消</el-button>
          <el-button type="primary" :disabled="!fileList.length" @click="uploadTemplate">
            开始导入
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入结果对话框 -->
    <el-dialog
      v-model="resultDialogVisible"
      title="导入结果"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="result-summary" v-if="importResult">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="总记录数">
            <span class="result-number">{{ importResult.totalRecords }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="成功记录数">
            <span class="result-number success">{{ importResult.successRecords }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="失败记录数">
            <span class="result-number error">{{ importResult.failedRecords }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resultDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="loadHistoryAndClose">查看数据</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 设备数据详情（原步骤3） -->
    <el-card class="step-card" v-if="currentStep === 'details'">
      <template #header>
        <div class="card-header">
          <h3>设备数据管理</h3>
          <div class="header-actions">
            <el-input
              v-model="searchText"
              placeholder="搜索厂站或设备"
              style="width: 300px; margin-right: 15px"
            />
            <el-button @click="loadHistoryData">查看历史数据</el-button>
          </div>
        </div>
      </template>

      <!-- 数据统计信息 -->
      <div class="data-summary">
        <el-descriptions :column="4" border>
          <el-descriptions-item label="厂站数量">{{
            stationGroups.length
          }}</el-descriptions-item>
          <el-descriptions-item label="设备总数">{{
            devices.length
          }}</el-descriptions-item>
          <el-descriptions-item label="最后更新时间">{{
            lastUpdateTime
          }}</el-descriptions-item>
          <el-descriptions-item label="数据状态">
            <el-tag :type="devices.length > 0 ? 'success' : 'warning'">
              {{ devices.length > 0 ? "数据完整" : "待导入" }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 按厂站分组展示设备数据 -->
      <div
        v-for="station in filteredStationGroups"
        :key="station.name"
        class="station-group"
      >
        <h4 class="station-title">{{ station.name }}</h4>

        <!-- 受令单位 -->
        <el-collapse>
          <el-collapse-item title="受令单位" name="commanding">
            <el-table :data="station.commandingUnits" size="small" stripe>
              <el-table-column prop="unitName" label="受令单位名称" />
              <el-table-column prop="updatedTime" label="更新时间" width="180">
                <template #default="scope">
                  {{ formatTime(scope.row.updatedTime) }}
                </template>
              </el-table-column>
            </el-table>
          </el-collapse-item>

          <el-collapse-item title="线路设备" name="line">
            <el-table :data="station.lineDevices" size="small" stripe>
              <el-table-column prop="voltageLevel" label="电压等级" width="100" />
              <el-table-column prop="deviceName" label="设备名称" />
              <el-table-column prop="deviceCode" label="设备编号" />
              <el-table-column prop="deviceType" label="设备类型" />
              <el-table-column prop="deviceDoubleCode" label="设备双编" min-width="200" />
              <el-table-column prop="updatedTime" label="更新时间" width="180">
                <template #default="scope">
                  {{ formatTime(scope.row.updatedTime) }}
                </template>
              </el-table-column>
            </el-table>
          </el-collapse-item>

          <el-collapse-item title="主变设备" name="transformer">
            <el-table :data="station.transformerDevices" size="small" stripe>
              <el-table-column prop="voltageLevel" label="电压等级" width="100" />
              <el-table-column prop="deviceName" label="设备名称" />
              <el-table-column prop="deviceCode" label="设备编号" />
              <el-table-column prop="deviceType" label="设备类型" />
              <el-table-column prop="deviceDoubleCode" label="设备双编" min-width="200" />
              <el-table-column prop="updatedTime" label="更新时间" width="180">
                <template #default="scope">
                  {{ formatTime(scope.row.updatedTime) }}
                </template>
              </el-table-column>
            </el-table>
          </el-collapse-item>

          <el-collapse-item title="母线及附属设备" name="bus">
            <el-table :data="station.busDevices" size="small" stripe>
              <el-table-column prop="voltageLevel" label="电压等级" width="100" />
              <el-table-column prop="deviceName" label="设备名称" />
              <el-table-column prop="deviceCode" label="设备编号" />
              <el-table-column prop="deviceType" label="设备类型" />
              <el-table-column prop="deviceDoubleCode" label="设备双编" min-width="200" />
              <el-table-column prop="updatedTime" label="更新时间" width="180">
                <template #default="scope">
                  {{ formatTime(scope.row.updatedTime) }}
                </template>
              </el-table-column>
            </el-table>
          </el-collapse-item>

          <el-collapse-item title="补充设备" name="supplement">
            <el-table :data="station.supplementDevices" size="small" stripe>
              <el-table-column prop="voltageLevel" label="电压等级" width="100" />
              <el-table-column prop="deviceName" label="设备名称" />
              <el-table-column prop="deviceCode" label="设备编号" />
              <el-table-column prop="deviceType" label="设备类型" />
              <el-table-column prop="deviceDoubleCode" label="设备双编" min-width="200" />
              <el-table-column prop="updatedTime" label="更新时间" width="180">
                <template #default="scope">
                  {{ formatTime(scope.row.updatedTime) }}
                </template>
              </el-table-column>
            </el-table>
          </el-collapse-item>
        </el-collapse>
      </div>

      <div class="step-actions">
        <el-button @click="backToUpload">重新导入</el-button>
        <el-button type="primary" @click="$router.push('/startup-plan')"
          >开始校验启动方案</el-button
        >
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { UploadFilled, View } from "@element-plus/icons-vue";
import { deviceTemplateApi } from "@/services/api";

// 响应式数据
const currentStep = ref("main");
const fileList = ref([]);
const importResult = ref(null);
const devices = ref([]);
const commandingUnits = ref([]);
const searchText = ref("");
const uploadDialogVisible = ref(false);
const resultDialogVisible = ref(false);

// 计算属性 - 按厂站分组
const stationGroups = computed(() => {
  const groups = new Map();

  // 安全检查
  if (!devices.value || devices.value.length === 0) {
    return [];
  }

  // 分组设备数据
  devices.value.forEach((device) => {
    if (!device || !device.stationName) return; // 安全检查

    if (!groups.has(device.stationName)) {
      groups.set(device.stationName, {
        name: device.stationName,
        lineDevices: [],
        transformerDevices: [],
        busDevices: [],
        supplementDevices: [],
        commandingUnits: [],
      });
    }

    const group = groups.get(device.stationName);
    switch (device.deviceCategory) {
      case "线路":
        group.lineDevices.push(device);
        break;
      case "主变":
        group.transformerDevices.push(device);
        break;
      case "母线及附属设备":
        group.busDevices.push(device);
        break;
      case "补充":
        group.supplementDevices.push(device);
        break;
    }
  });

  // 添加受令单位数据 - 受令单位是全局的，每个厂站都显示相同的受令单位
  const globalCommandingUnits = [...(commandingUnits.value || [])];
  groups.forEach((group) => {
    group.commandingUnits = [...globalCommandingUnits];
  });

  return Array.from(groups.values());
});

const filteredStationGroups = computed(() => {
  if (!stationGroups.value || stationGroups.value.length === 0) return [];
  if (!searchText.value) return stationGroups.value;

  return stationGroups.value.filter(
    (station) =>
      station &&
      station.name &&
      (station.name.includes(searchText.value) ||
        (station.lineDevices &&
          station.lineDevices.some(
            (device) =>
              (device &&
                device.deviceName &&
                device.deviceName.includes(searchText.value)) ||
              (device &&
                device.deviceDoubleCode &&
                device.deviceDoubleCode.includes(searchText.value))
          )) ||
        (station.transformerDevices &&
          station.transformerDevices.some(
            (device) =>
              (device &&
                device.deviceName &&
                device.deviceName.includes(searchText.value)) ||
              (device &&
                device.deviceDoubleCode &&
                device.deviceDoubleCode.includes(searchText.value))
          )) ||
        (station.busDevices &&
          station.busDevices.some(
            (device) =>
              (device &&
                device.deviceName &&
                device.deviceName.includes(searchText.value)) ||
              (device &&
                device.deviceDoubleCode &&
                device.deviceDoubleCode.includes(searchText.value))
          )) ||
        (station.supplementDevices &&
          station.supplementDevices.some(
            (device) =>
              (device &&
                device.deviceName &&
                device.deviceName.includes(searchText.value)) ||
              (device &&
                device.deviceDoubleCode &&
                device.deviceDoubleCode.includes(searchText.value))
          )))
  );
});

// 是否有历史数据（仅根据设备数据判断）
const hasHistoryData = computed(() => {
  return devices.value.length > 0;
});

// 清空覆写/导入新增
const do_clear = ref(true);

const lastUpdateTime = computed(() => {
  if (devices.value.length === 0) return "暂无数据";
  const latestTime = devices.value.reduce((latest, device) => {
    return new Date(device.updatedTime) > new Date(latest) ? device.updatedTime : latest;
  }, devices.value[0].updatedTime);
  return formatTime(latestTime);
});

// 方法
const handleFileChange = (file: any, uploadFileList: any[]) => {
  fileList.value = uploadFileList;
};

// 显示上传对话框
const showUploadDialog = () => {
  fileList.value = [];
  uploadDialogVisible.value = true;
};

// 上传模板
const uploadTemplate = async () => {
  if (fileList.value.length === 0) {
    ElMessage.warning("请先选择文件");
    return;
  }

  try {
    ElMessage.info("开始导入设备模板...");
    const response = await deviceTemplateApi.upload(
      fileList.value[0].raw,
      do_clear.value,
      "设备模板导入",
    );
    importResult.value = response;
    uploadDialogVisible.value = false;
    resultDialogVisible.value = true;
    ElMessage.success("设备模板导入完成");
  } catch (error) {
    ElMessage.error("导入失败: " + (error.message || "未知错误"));
  }
};

// 加载历史数据并关闭结果对话框
const loadHistoryAndClose = async () => {
  try {
    await loadHistoryData();
    resultDialogVisible.value = false;
  } catch (error) {
    ElMessage.error("加载数据失败: " + error.message);
  }
};

// 查看历史数据
const viewHistoryData = async () => {
  try {
    await loadHistoryData();
    currentStep.value = "history";

    // 不显示消息提示，让页面的空状态组件来处理显示
  } catch (error) {
    ElMessage.error("加载历史数据失败: " + error.message);
    // 即使出错也跳转到历史页面，显示无数据提示
    currentStep.value = "history";
  }
};

// 使用历史数据继续校验
const continueWithHistory = () => {
  ElMessage.success("即将进入启动方案校验页面");
  // 跳转到启动方案校验页面
  setTimeout(() => {
    window.open("/startup-plan", "_self");
  }, 1000);
};

// 时间格式化
const formatTime = (time: string) => {
  if (!time) return "暂无";
  return new Date(time).toLocaleString("zh-CN");
};

// 查看历史数据
const loadHistoryData = async () => {
  try {
    const [devicesResponse, commandingUnitsResponse] = await Promise.all([
      deviceTemplateApi.getDevices(),
      deviceTemplateApi.getCommandingUnits(),
    ]);
    devices.value = devicesResponse || [];
    commandingUnits.value = commandingUnitsResponse || [];

    console.log(
      `加载了 ${devicesResponse?.length || 0} 条设备数据和 ${
        commandingUnitsResponse?.length || 0
      } 个受令单位`
    );
    console.log(`hasHistoryData: ${devices.value.length > 0}`);
  } catch (error) {
    console.error("加载历史数据失败:", error);
    // 确保即使出错也设置空数组，这样页面能正常显示"无数据"提示
    devices.value = [];
    commandingUnits.value = [];
  }
};

// 页面加载时不自动获取数据，等用户选择操作
onMounted(() => {
  // 不自动加载数据，由用户主动选择
});
</script>

<style scoped>
.device-template {
  padding: 40px 0;
}

.page-header {
  text-align: center;
  margin-bottom: 60px;
}

.page-header h2 {
  font-size: 28px;
  color: #2c3e50;
  margin-bottom: 15px;
}

.page-header p {
  font-size: 16px;
  color: #606266;
}

.main-card {
  margin-bottom: 40px;
  min-height: 500px;
}

.step-card {
  margin-bottom: 40px;
  min-height: 400px;
}

.step-card .el-card__header h3 {
  margin: 0;
  font-size: 20px;
  color: #2c3e50;
}

.upload-area {
  padding: 40px 0;
}

.upload-dragger {
  width: 100%;
}

.upload-icon {
  font-size: 64px;
  color: #c0c4cc;
  margin-bottom: 20px;
}

.upload-text p {
  margin: 10px 0;
  font-size: 16px;
  color: #606266;
}

.upload-tip {
  font-size: 14px !important;
  color: #909399 !important;
}

.step-actions {
  text-align: center;
  margin-top: 40px;
}

.result-summary {
  margin: 40px 0;
}

.result-number {
  font-size: 18px;
  font-weight: bold;
}

.result-number.success {
  color: #67c23a;
}

.result-number.error {
  color: #f56c6c;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 20px;
  color: #2c3e50;
}

/* 修复表格文字颜色 */
.el-table {
  color: #2c3e50 !important;
}

.el-table td,
.el-table th {
  color: #2c3e50 !important;
}

.el-table .cell {
  color: #2c3e50 !important;
}

/* 表格头部样式 */
.el-table th {
  background-color: #fafafa !important;
  color: #2c3e50 !important;
  font-weight: 600 !important;
}

/* 表格行样式 */
.el-table tr {
  background-color: #ffffff !important;
}

.el-table tr:nth-child(even) {
  background-color: #f8f9fa !important;
}

/* 新增样式 */
.no-data-hint {
  text-align: center;
  padding: 80px 0;
}

.empty-description h4 {
  margin: 16px 0 12px 0;
  color: #2c3e50;
  font-size: 18px;
  font-weight: 600;
}

.empty-description p {
  margin: 8px 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
}

.empty-description .empty-tip {
  color: #909399;
  font-size: 13px;
  margin-top: 16px;
}

.empty-actions {
  margin-top: 24px;
}

.empty-actions .el-button {
  padding: 12px 24px;
  border-radius: 6px;
}

.search-bar {
  margin-bottom: 20px;
}

.history-data {
  margin-top: 30px;
}

.upload-dialog-content .mt-20 {
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.data-summary {
  margin: 20px 0;
}

.station-group {
  margin-bottom: 30px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  overflow: hidden;
}

.station-title {
  margin: 0;
  padding: 15px 20px;
  background-color: #f5f7fa;
  color: #2c3e50;
  font-size: 18px;
  border-bottom: 1px solid #e4e7ed;
}

.el-collapse {
  border: none;
}

.el-collapse-item {
  border-bottom: 1px solid #e4e7ed;
}

.el-collapse-item:last-child {
  border-bottom: none;
}
</style>
